import requests
import json
import time
import random
import hashlib


def fanyi(keyword):
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"

    #定义请求参数
    e = keyword
    t = str(int(time.time()*1000) + random.randint(1,10))
    sign  = hashlib.md5(("fanyideskweb" + e + t + "sr_3(QOHT)L2dx#uuGR@r").encode('utf-8')).hexdigest()

    data = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': t,
        'sign': sign,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_CLICKBUTTION',
        'typoResult': 'false',
        }
    res = requests.post(url,data=data)

    #解析并输出
    str_json = res.content.decode('utf-8')
    myjson = json.loads(str_json)
    
    print("结果是：%s" % myjson['translateResult'][0][0]['tgt'])

if __name__=='__main__':
    while True:
        keyword = input('请输入需要翻译的单词：')
        if keyword =='q':
            break
        fanyi(keyword)
